package com.matt.service.impl;

import com.fasterxml.jackson.databind.JavaType;
import com.matt.domain.*;
import com.matt.commons.dto.sso.StaffDTO;
import com.matt.foundation.utils.ContrastStringFromOldAndNow;
import com.matt.foundation.utils.DateUtil;
import com.matt.foundation.utils.ModelUtil;
import com.matt.foundation.vo.ClienteleSaveVo;
import com.matt.repository.*;
import com.matt.service.LeadsOperationLogService;
import com.matt.remoteCall.SsoCallService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.matt.foundation.constant.OperateConstant.*;

/**
 * ***********************
 * Created by Ron
 * from com.matt
 * on 2018/7/23 0023.
 * ***********************
 */
@Transactional
@Service
public class LeadsOperationLogServiceImpl implements LeadsOperationLogService {

    @Autowired
    private LeadsHistoryRepository leadsHistoryRepository;
    @Autowired
    private LeadsRepository leadsRepository;
    @Autowired
    private SsoCallService ssoCallService;
    @Autowired
    private ClienteleRepository clienteleRepository;
    @Autowired
    private ContractRepository contractRepository;
    @Autowired
    private ContractHistoryRepository contractHistoryRepository;
    @Autowired
    private ProductRepository productRepository;
    @Autowired
    private LeadsUserRepository leadsUserRepository;


    @Override
    public LeadsHistory createLeads(Leads leads,String ticket, String code) {
        Date date =new Date();
        StaffDTO baseInfo =new StaffDTO();
        String id = "";
        String realName = "";
        String headImgUrl = "";
        String areaId = "";
        if (StringUtils.isNotBlank(ticket)){
            baseInfo = ssoCallService.getStaffDTO(ticket);
            id = baseInfo.getId();
             realName = baseInfo.getRealName();
             headImgUrl = baseInfo.getHeadImgUrl();
             areaId = baseInfo.getAreaId();
        }else {
            areaId = leads.getAreaId();
        }

        //修改
        if (StringUtils.isNotBlank(leads.getId())){
            LeadsHistory leadsHistory = new LeadsHistory();
            leadsHistory.setStaffName(leads.getStaffName());
            leadsHistory.setType("leads");
            leadsHistory.setOperationType(OPERATE_UPDATE);
            Leads old=leadsRepository.getOne(leads.getId());
            //过滤掉不记录的信息
            leads.setChangeStatus(old.getChangeStatus());
            leads.setChannelStatus(old.getChannelStatus());
            leads.setClientStatus(old.getClientStatus());
            leads.setFromUserId(old.getFromUserId());
            //leads.setChangeStatus(old.getChangeStatus());
            leads.setStaffId(old.getStaffId());
            leads.setCreated(old.getCreated());
            leads.setDeleted(old.getDeleted());
            leads.setStaffName(old.getStaffName());
            leads.setAreaId(old.getAreaId());
            leads.setStatus(old.getStatus());
            //特殊处理字段
            leads.setBirthday(DateUtil.sqlDate(leads.getBirthday()));
            old.setBirthday(DateUtil.sqlDate(old.getBirthday()));

            //申明两个对象
            Leads oldBean = new Leads();
            Leads nowBean = new Leads();
            BeanUtils.copyProperties(old,oldBean);
            BeanUtils.copyProperties(leads,nowBean);

            String changeInfo=new ContrastStringFromOldAndNow<Leads>().contrastObj(oldBean,nowBean);
            leadsHistory.setContent( "在 "+DateUtil.dateToymd(date)+" 修改了本条数据 "+'\n' +changeInfo);
            leadsHistory.setActualFollowDate(date);
            leadsHistory.setLeadsId(leads.getId());
            leadsHistory.setStaffId(id);
            leadsHistory.setStaffName(realName);
            leadsHistory.setStaffHeadImgUrl(headImgUrl);
            leadsHistory.setAreaId(areaId);
            return leadsHistoryRepository.save(leadsHistory);
        }

       return null;
    }

    @Override
    public LeadsHistory deleteById(String leadsId, String ticket, String code) {
        Date date = new Date();
        StaffDTO baseInfo = ssoCallService.getStaffDTO(ticket);
        LeadsHistory leadsHistory = new LeadsHistory();

        leadsHistory.setType("leads");
        leadsHistory.setOperationType(OPERATE_DELETE);
        leadsHistory.setContent("在 "+DateUtil.dateToymd(date)+" 删除了本条数据");
        leadsHistory.setActualFollowDate(date);
        leadsHistory.setLeadsId(leadsId);
        leadsHistory.setStaffId(baseInfo.getId());
        leadsHistory.setStaffName(baseInfo.getRealName());
        leadsHistory.setStaffHeadImgUrl(baseInfo.getHeadImgUrl());
        leadsHistory.setAreaId(baseInfo.getAreaId());
        return leadsHistoryRepository.save(leadsHistory);
    }

    @Override
    public LeadsHistory changeStaffInfo(String ticket,String staffId, String staffName, String leadsId) {
        Date date = new Date();
        Leads leads = leadsRepository.getOne(leadsId);
        StaffDTO baseInfo = ssoCallService.getStaffDTO(ticket);
        LeadsHistory leadsHistory = new LeadsHistory();
        leadsHistory.setType("leads");
        leadsHistory.setOperationType(OPERATE_TRANSFER);
        leadsHistory.setContent("在 "+DateUtil.dateToymd(date)+" 将本数据转移给了 \""+staffName+"\"");
        leadsHistory.setActualFollowDate(date);
        leadsHistory.setLeadsId(leadsId);
        leadsHistory.setStaffId(baseInfo.getId());
        leadsHistory.setStaffName(baseInfo.getRealName());
        leadsHistory.setStaffHeadImgUrl(baseInfo.getHeadImgUrl());
        leadsHistory.setAreaId(baseInfo.getAreaId());
        return leadsHistoryRepository.save(leadsHistory);
    }

    @Override
    public LeadsHistory changeClientele(String ticket,ClienteleSaveVo clienteleSaveVo,String productRecords) {
       //计算预计价格
        String preferProductStr = "";
        BigDecimal preMoney=new BigDecimal(0);
        if(productRecords != null && !"".equals(productRecords)){
            //反序列号
            JavaType javaType = ModelUtil.objectMapper.getTypeFactory().constructParametricType(ArrayList.class, ContractProduct.class);
            try {
                List<ContractProduct> contractProducts = ModelUtil.objectMapper.readValue(productRecords, javaType);
                for (ContractProduct cp : contractProducts) {
                    Product product = productRepository.getOne(cp.getProductId());
                    preferProductStr += "“" + product.getName() +"” " + cp.getCount() + product.getUnit() + "，";
                    preMoney = preMoney.add(product.getStandardAmount().multiply(new BigDecimal(cp.getCount())));
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("json 转集合对象异常");
            }
        }

        Date date= new Date();
        Leads leads = leadsRepository.getOne(clienteleSaveVo.getLeadsId());
        StaffDTO baseInfo = ssoCallService.getStaffDTO(ticket);
        LeadsHistory leadsHistory = new LeadsHistory();
        leadsHistory.setType("leads");
        leadsHistory.setContent("在 "+DateUtil.dateToymd(date)+" 将此线索转为了客户"+'\n'+
                ((preMoney.intValue() != 0 )
                ? "意向产品" + preferProductStr + "，预计收入为 \""+preMoney.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue()+" \" 元"
                : "线索没有添加意向产品，无预计收入。")
        );
        leadsHistory.setActualFollowDate(date);
        leadsHistory.setLeadsId(clienteleSaveVo.getLeadsId());
        leadsHistory.setStaffId(baseInfo.getId());
        leadsHistory.setStaffName(baseInfo.getRealName());
        leadsHistory.setStaffHeadImgUrl(baseInfo.getHeadImgUrl());
        leadsHistory.setAreaId(baseInfo.getAreaId());
        return leadsHistoryRepository.save(leadsHistory);
    }

    @Override
    public LeadsHistory uploadAttachment(String ticket, Attachment attachment) {
        Date date=new Date();
        StaffDTO baseInfo = ssoCallService.getStaffDTO(ticket);

        if (StringUtils.isNotBlank(attachment.getContractId()) && StringUtils.isNotBlank(attachment.getClienteleId())){
            //合同附件上传时
            Contract contract = contractRepository.getOne(attachment.getContractId());
            ContractHistory contractHistory = new ContractHistory();
            contractHistory.setOperationType(OPERATE_UPLOAD);
            contractHistory.setContent("在 "+DateUtil.dateToymd(date)+" 上传了附件") ;
            contractHistory.setClienteleId(attachment.getClienteleId());
            contractHistory.setStaffId(baseInfo.getId());
            contractHistory.setStaffName(baseInfo.getRealName());
            contractHistory.setStaffHeadImgUrl(baseInfo.getHeadImgUrl());
            contractHistory.setContractId(contract.getId());
            contractHistoryRepository.save(contractHistory);
        }else{
            LeadsHistory leadsHistory = new LeadsHistory();
            //线索附件上传时
            if (StringUtils.isNotBlank(attachment.getLeadsId()) && StringUtils.isBlank(attachment.getClienteleId())){
                Leads leads = leadsRepository.getOne(attachment.getLeadsId());
                leadsHistory.setType("leads");
                leadsHistory.setLeadsId(attachment.getLeadsId());
                leadsHistory.setOperationType(OPERATE_UPLOAD);
                leadsHistory.setAttachmentUrl(attachment.getAttachmentUrl());
                leadsHistory.setContent("在 "+DateUtil.dateToymd(date)+" 上传了附件") ;
            }
            //客户附件上传
            if (StringUtils.isNotBlank(attachment.getClienteleId()) && StringUtils.isNotBlank(attachment.getLeadsId()) ){
                Clientele clientele = clienteleRepository.getOne(attachment.getClienteleId());
                leadsHistory.setClientelesId(attachment.getClienteleId());
                leadsHistory.setType("clientele");
                leadsHistory.setLeadsId(attachment.getLeadsId());
                leadsHistory.setOperationType(OPERATE_UPLOAD);
                leadsHistory.setAttachmentUrl(attachment.getAttachmentUrl());
                leadsHistory.setContent("在 "+DateUtil.dateToymd(date)+" 上传了附件") ;
            }

            leadsHistory.setAreaId(baseInfo.getAreaId());
            leadsHistory.setActualFollowDate(new Date());
            leadsHistory.setLeadsId(attachment.getLeadsId());
            leadsHistory.setStaffId(baseInfo.getId());
            leadsHistory.setStaffName(baseInfo.getRealName());
            leadsHistory.setStaffHeadImgUrl(baseInfo.getHeadImgUrl());
            return leadsHistoryRepository.save(leadsHistory);
        }
       return null;
    }

    @Override
    public LeadsHistory updateClientele(String ticket, Clientele clientele) {
        Date date = new Date();
        StaffDTO baseInfo = ssoCallService.getStaffDTO(ticket);
        LeadsHistory leadsHistory = new LeadsHistory();
        leadsHistory.setType("clientele");

        Clientele old = clienteleRepository.getOne(clientele.getId());
        //过滤掉不需要的信息
        clientele.setCreated(old.getCreated());
        clientele.setDeleted(old.getDeleted());
        clientele.setChannelId(old.getChannelId());
        clientele.setFromUserId(old.getFromUserId());
        clientele.setChildName(old.getChildName());
        clientele.setStaffId(old.getStaffId());
        clientele.setLeadsId(old.getLeadsId());
        clientele.setStatus(old.getStatus());
        clientele.setStaffName(old.getStaffName());
        clientele.setAreaId(old.getAreaId());
        clientele.setLastFollowTime(old.getLastFollowTime());
        clientele.setLastFollowRecord(old.getLastFollowRecord());
        clientele.setLastModified(date);
        clientele.setLastModifiedId(baseInfo.getId());
        //特殊处理字段
        clientele.setBirthday(DateUtil.sqlDate(clientele.getBirthday()));
        old.setBirthday(DateUtil.sqlDate(old.getBirthday()));

        //申明两个对象
        Clientele oldBean = new Clientele();
        Clientele nowBean = new Clientele();
        BeanUtils.copyProperties(old,oldBean);
        BeanUtils.copyProperties(clientele,nowBean);

        String changeInfo = new ContrastStringFromOldAndNow<Clientele>().contrastObj(oldBean,nowBean);
        leadsHistory.setContent("在 "+DateUtil.dateToymd(date)+" 修改了本条数据 "+'\n' +changeInfo);
        leadsHistory.setActualFollowDate(date);
        leadsHistory.setLeadsId(clientele.getLeadsId());
        leadsHistory.setClientelesId(clientele.getId());
        leadsHistory.setStaffId(baseInfo.getId());
        leadsHistory.setStaffHeadImgUrl(baseInfo.getHeadImgUrl());
        leadsHistory.setStaffName(baseInfo.getRealName());
        leadsHistory.setAreaId(baseInfo.getAreaId());

        return leadsHistoryRepository.save(leadsHistory);
    }

    @Override
    public LeadsHistory updateClienteleStaff(String ticket, String staffId, String staffName, String clienteleId) {
        Date date = new Date();
        StaffDTO baseInfo = ssoCallService.getStaffDTO(ticket);
        LeadsHistory leadsHistory = new LeadsHistory();
        Clientele clientele = clienteleRepository.getOne(clienteleId);
        leadsHistory.setOperationType(OPERATE_TRANSFER);
        leadsHistory.setType("clientele");
        leadsHistory.setContent( "在 "+DateUtil.dateToymd(date)+" 将本数据转移给了 \"" + staffName+"\"");
        leadsHistory.setActualFollowDate(date);
        leadsHistory.setLeadsId(clientele.getLeadsId());
        leadsHistory.setClientelesId(clienteleId);
        leadsHistory.setStaffId(baseInfo.getId());
        leadsHistory.setStaffName(baseInfo.getRealName());
        leadsHistory.setStaffHeadImgUrl(baseInfo.getHeadImgUrl());
        leadsHistory.setAreaId(baseInfo.getAreaId());

        return leadsHistoryRepository.save(leadsHistory);
    }

    @Override
    public LeadsHistory addContractForClientele(StaffDTO baseInfo, Contract contract) {
        //1.添加客户那边的操作日志
        Date date = new Date();

        LeadsHistory leadsHistory = new LeadsHistory();
        Clientele clientele = clienteleRepository.getOne(contract.getClienteleId());
        leadsHistory.setOperationType(OPERATE_CREATE);
        leadsHistory.setType("clientele");
        leadsHistory.setContent( "在 "+DateUtil.dateToymd(date)+" 添加了合同 "+'\n'+" 合同编号 "+contract.getCode());
        leadsHistory.setActualFollowDate(date);
        leadsHistory.setLeadsId(clientele.getLeadsId());
        leadsHistory.setClientelesId(contract.getClienteleId());
        leadsHistory.setStaffId(baseInfo.getId());
        leadsHistory.setStaffName(baseInfo.getRealName());
        leadsHistory.setStaffHeadImgUrl(baseInfo.getHeadImgUrl());
        leadsHistory.setAreaId(baseInfo.getAreaId());
        LeadsHistory vo= leadsHistoryRepository.save(leadsHistory);
        return vo;
    }

    @Override
    public LeadsHistory deleteClientele(String ticket, String clienteleId) {
        Date date = new Date();
        StaffDTO baseInfo = ssoCallService.getStaffDTO(ticket);
        LeadsHistory leadsHistory = new LeadsHistory();
        Clientele clientele = clienteleRepository.getOne(clienteleId);
        leadsHistory.setType("clientele");
        leadsHistory.setContent( "在 "+DateUtil.dateToymd(date)+" 删除了本条数据" );
        leadsHistory.setActualFollowDate(date);
        leadsHistory.setLeadsId(clientele.getLeadsId());
        leadsHistory.setClientelesId(clienteleId);
        leadsHistory.setStaffId(baseInfo.getId());
        leadsHistory.setStaffName(baseInfo.getRealName());
        leadsHistory.setStaffHeadImgUrl(baseInfo.getHeadImgUrl());
        leadsHistory.setAreaId(baseInfo.getAreaId());
        return leadsHistoryRepository.save(leadsHistory);
    }

    @Override
    public LeadsHistory createLead(LeadsUser leadsUser, String ticket, String code) {
        Date date =new Date();
        StaffDTO baseInfo = ssoCallService.getStaffDTO(ticket);
        Leads leads = leadsRepository.findById(leadsUser.getLeadsId()).get();

        //修改
        if (StringUtils.isNotBlank(leadsUser.getId())){
            LeadsHistory leadsHistory = new LeadsHistory();
            leadsHistory.setStaffName(leads.getStaffName());
            leadsHistory.setType("leads");
            leadsHistory.setOperationType(OPERATE_UPDATE);
            LeadsUser old=leadsUserRepository.getOne(leadsUser.getId());
            //过滤掉不记录的信息
            leadsUser.setCreated(old.getCreated());
            leadsUser.setDeleted(old.getDeleted());
            leadsUser.setAreaId(old.getAreaId());
            leadsUser.setLeadsId(old.getLeadsId());
            leadsUser.setChildBigName(old.getChildBigName());

            //申明两个对象
            LeadsUser oldBean = new LeadsUser();
            LeadsUser nowBean = new LeadsUser();
            BeanUtils.copyProperties(old,oldBean);
            BeanUtils.copyProperties(leadsUser,nowBean);

            String changeInfo=new ContrastStringFromOldAndNow<LeadsUser>().contrastObj(oldBean,nowBean);
            leadsHistory.setContent( "在 "+DateUtil.dateToymd(date)+" 修改了本条数据 "+'\n' +changeInfo);
            leadsHistory.setActualFollowDate(date);
            leadsHistory.setLeadsId(leads.getId());
            leadsHistory.setStaffId(baseInfo.getId());
            leadsHistory.setStaffName(baseInfo.getRealName());
            leadsHistory.setStaffHeadImgUrl(baseInfo.getHeadImgUrl());
            leadsHistory.setAreaId(baseInfo.getAreaId());
            return leadsHistoryRepository.save(leadsHistory);
        }

        return null;
    }
}
